from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework.response import Response

from rest_framework.viewsets import ModelViewSet

from apps.goods.models import Brand
from apps.meiduo_admin.serializers.brands import BrandsModelSer
from apps.meiduo_admin.utils.MeiduoPage import PageNum


class BrandsModelViewSet(ModelViewSet):
    pagination_class = PageNum
    queryset = Brand.objects.all()
    serializer_class = BrandsModelSer

    def create(self, request, *args, **kwargs):
        client = Fdfs_client(settings.FASTDFS_CLIENT_CONF)
        image = request.data.get('logo')
        name = request.data.get('name')
        first_letter = request.data.get('first_letter')
        res = client.upload_by_buffer(image.read())
        image_url = res['Remote file_id']
        brand=Brand.objects.create(name=name,first_letter=first_letter,logo=image_url)
        instance = self.get_serializer(brand)
        return Response(instance.data,status=201)

    def update(self, request, *args, **kwargs):
        instance = self.get_object()
        name = request.data.get('name')
        image = request.data.get('logo')
        first_letter = request.data.get('first_letter')


        client = Fdfs_client(settings.FASTDFS_CLIENT_CONF)
        client.delete_file(instance.logo.name)
        res = client.upload_by_buffer(image.read())
        img_url = res['Remote file_id']
        instance.logo = img_url

        instance.save()

        serializer = self.get_serializer(instance)
        return Response(serializer.data, status=201)


